import { http } from '../api/axios';
import { ExecutionRecord } from '../contexts/types';

/**
 * 检查是否为日期对象
 */
const isDate = (value: any): value is Date => {
  return value instanceof Date && !isNaN(value.getTime());
};

/**
 * 获取执行记录列表
 * @param params 可选的查询参数
 */
export const getExecutionRecords = async (params?: {
  skip?: number;
  limit?: number;
  taskId?: string;
}): Promise<ExecutionRecord[]> => {
  const response = await http.get<ExecutionRecord[]>('/records/', { params });
  
  // 转换日期字符串为Date对象
  return response.map(record => ({
    ...record,
    createdAt: new Date(record.createdAt),
    logs: Array.isArray(record.logs) ? record.logs.map(log => ({
      ...log,
      createdAt: typeof log.createdAt === 'string' ? log.createdAt : log.createdAt
    })) : []
  }));
};

/**
 * 创建新执行记录
 */
export const createExecutionRecord = async (
  record: Omit<ExecutionRecord, 'id' | 'createdAt'>
): Promise<ExecutionRecord> => {
  // 转换日期格式和处理 logs
  const processedRecord = {
    ...record,
    logs: record.logs.map(log => ({
      ...log,
      // 确保日期格式是字符串
      createdAt: isDate(log.createdAt) ? log.createdAt.toISOString() : log.createdAt
    }))
  };
  
  const response = await http.post<ExecutionRecord>('/records/', processedRecord);
  
  // 转换返回的数据中的日期字符串为Date对象
  return {
    ...response,
    createdAt: new Date(response.createdAt),
    logs: Array.isArray(response.logs) ? response.logs.map(log => ({
      ...log,
      createdAt: typeof log.createdAt === 'string' ? log.createdAt : log.createdAt
    })) : []
  };
};

/**
 * 更新执行记录
 */
export const updateExecutionRecord = async (
  id: string,
  record: Partial<ExecutionRecord>
): Promise<ExecutionRecord> => {
  // 如果更新包含 logs，确保处理日期格式
  const processedRecord = record.logs ? {
    ...record,
    logs: record.logs.map(log => ({
      ...log,
      createdAt: isDate(log.createdAt) ? log.createdAt.toISOString() : log.createdAt
    }))
  } : record;

  const response = await http.put<ExecutionRecord>(`/records/${id}`, processedRecord);
  
  // 转换返回的数据中的日期字符串为Date对象
  return {
    ...response,
    createdAt: new Date(response.createdAt),
    logs: Array.isArray(response.logs) ? response.logs.map(log => ({
      ...log,
      createdAt: typeof log.createdAt === 'string' ? log.createdAt : log.createdAt
    })) : []
  };
};

/**
 * 删除执行记录
 */
export const deleteExecutionRecord = async (id: string): Promise<void> => {
  await http.delete(`/records/${id}`);
};

// 导出所有执行记录相关操作
const recordService = {
  getExecutionRecords,
  createExecutionRecord,
  updateExecutionRecord,
  deleteExecutionRecord,
};

export default recordService; 